var util = require('../../util/util.js')
var formatLocation = util.formatLocation

let app = getApp();
let jumpurl=app.jumpurl.url;
var bmap = require('../../libs/bmap-wx.js');
var wxMarkerData = [];
var lishi = [];
var address;
var addresslist=[];
var id_now;
let c_location;
var c_latitude;
var c_longitude;
var historyList=[];
let currentTab;

Page({
  data: {
    winHeight: "",//窗口高度
    currentTab1: 0, //预设当前项的值
    scrollLeft: 0, //tab标题的滚动条位置
   addresslist:[{
     title:111,
     addr:"jiangsuzhousheng"
   },{
     title:"徐州万创网络科技有限公司",
       addr: "江苏省徐州市鼓楼区创意文化科技产业园A2-1楼"
     },
   ],
   addrlist:[{
      id:1,
      name:"zhangsan",
      tel:"13625632541",
     address:"江苏省徐州市鼓楼区创意文化科技产业园A2-1楼江苏省徐州市鼓楼区创意文化科技产业园A2-1楼"
   },{
       id: 2,
       name: "李四",
       tel: "13625632541",
       address: "江苏省徐州市鼓楼区黄河北路90号"
     }, {
       id: 3,
       name: "韩梅梅",
       tel: "13625632541",
       address: "江苏省徐州市鼓楼区黄河北路90号"
     }
     ],
    
   
    history_flag:true,
    addr_grey_flag:false,
    hasaddr:false,
    gobackflag:false
    
    // 百度地图
    // markers: [],
    // latitude: '',
    // longitude: '',
    // placeData: {} 

  },
  // makertap: function (e) {
  //   var that = this;
  //   var id = e.markerId;
  //   that.showSearchInfo(wxMarkerData, id);
  //   that.changeMarkerColor(wxMarkerData, id);
  // }, 
  // 滚动切换标签样式
  switchTab: function (e) {
    this.setData({
      currentTab1: e.detail.current
    });
    this.checkCor();
  },
  // 点击标题切换当前页时改变样式
  swichNav: function (e) {
    var cur = e.target.dataset.current;
    if (this.data.currentTaB == cur) { return false; }
    else {
      this.setData({
        currentTab1: cur
      })
    }
  },
  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function () {
    if (this.data.currentTab > 4) {
      this.setData({
        scrollLeft: 300
      })
    } else {
      this.setData({
        scrollLeft: 0
      })
    }
  },
  onLoad: function (options) {
    var that = this;
    var jumpurl=app.jumpurl.url;
    currentTab=options.id;
     that.setData({
       currentTab: options.id,
    
     })
  
   
    //请求数据
    wx.request({
      url: jumpurl+'address/name',
      data:{
        currentTab: options.id,
        openid:app.userList.openid
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //post
      },
      success:function(res){
        if(res.data.faaddress.length>0){
          var fhr = res.data.faaddress[0].name;
          var tel = res.data.faaddress[0].tel;
          that.setData({
            setname: fhr,
            phone: tel
          })
        }
         
      },
      fail:function(err){
        console.log(err);
      }
    })

   
    
    //  id_now=options.id;

    //  20180712modify
     ///获取定位信息
     wx.getLocation({
       type: 'wgs84',
       success: function (res) {
         console.log(res);
          that.setData({
            location: formatLocation(res.longitude, res.latitude),
            latitude:res.latitude,
            longitude:res.longitude,
            
            markers: [{
              id: 1,
              latitude: res.latitude,
              longitude: res.longitude,

            }],
            covers: [{
              latitude: res.latitude,
              longitude: res.longitude,
              iconPath: 'images/location.png'
            }, {
                latitude: res.latitude,
                longitude: res.longitude,
                iconPath: 'images/location.png'
            }]
         })


       }
     })
    var BMap = new bmap.BMapWX({
      ak: 'bzQsfmU86UsaqMOeZzXFrjbkVAUKcVYW'
    }); 
    // 发起POI检索请求 
    BMap.search({
      "query": '办公楼',
      fail: function(err){
          console.log("err"+err);
      },
      success: function(res){
        addresslist=res.wxMarkerData;
         console.log("****************addresslist***************")
          console.log(addresslist);
          that.setData({
             addresslist:addresslist
          })
      },
     
    }); 

   
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 180;
        that.setData({
          winHeight: calc
        });
      }
    });


    /***********判断地址选中********** */
    that.setData({
      chosedItem:1
     
    })

 
 },
   
/**********onshow**********/
onShow:function(){
  var that=this;
    wx.getStorage({
      key: 'title',
      success: function(res) {
        console.log(res);
        that.setData({
          locationAddress:res.data
        })
      },
      fail:function(err){
        console.log("调用缓存"+err)
      }
    })

  wx.getStorage({
    key: 'title_key',
    success: function (res) {
      console.log(res);
      that.setData({
        locationAddress: res.data,
        address2:""
      })
    },
    fail: function (err) {
      console.log("调用缓存" + err)
    }
  })

  // wx.getStorage({
  //   key: 'map_add_key',
  //   success: function (res) {
  //     console.log(res);
  //     that.setData({
  //       locationAddress: res.data
  //     })
  //   },
  //   fail: function (err) {
  //     console.log("调用缓存" + err)
  //   }
  // })

  wx.getStorage({
    key: 'jingwei_key',
    success: function (res) {
      console.log(res);
      that.setData({
        jingwei: res.data
      })
    },
    fail: function (err) {
      console.log("调用缓存" + err)
    }
  })

  //调取历史地址
  wx.request({
    url: jumpurl +'history/fa',
    data:{
      openid:app.userList.openid
    },
    success:function(res){
     
      var lishi_address=res.data.falishi;
     
      if(lishi_address==0){
        that.setData({
          history_flag:false
        })
      }else{
        that.setData({
          history_flag:true,
          lishi:lishi_address
        })
      }
    },
    fail:function(err){
      console.log("调用历史地址"+err)
      }
  })
},



 /******监听返回事件************/
  goback:function(e){
    console.log(e)
    var that=this;
    console.log(that);
    var currentTab= that.data.currentTab;
    console.log(currentTab)
    wx.showModal({
      title: '',
      content: '确定放弃本次编辑',
      showCancel:true,
      cancelText:"取消",
      cancelColor:"#666",
      confirmText:"确定",
      confirmColor:"#ffae58",
      success:function(res){
        if (res.confirm) {
          console.log('用户点击确定');
          wx.setStorage({
            key: 'map_add_key',
            data: '',
          })
          wx.setStorage({
            key: 'title_key',
            data: '',
          })
          wx.setStorage({
            key: 'jingwei_key',
            data: '',
          })
          wx.redirectTo({
            url: '/pages/index/index?currentTab=' + that.data.currentTab,
          })
         
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }, fail:function(){
        console.log("fail");
      }

    })
    // that.setData({
    //   gobackflag:true
    // })
  },
  cancel:function(){
    var that=this;
    that.setData({
      gobackflag: false
    })
  },
  comfirm:function(){
    var that = this;
    that.setData({
      gobackflag: false
    })
    wx.redirectTo({
      url: '/pages/index/index?currentTab=' + that.data.currentTab,
    })
  },
 
 chooseLocation: function () {
  
    var that = this;
    wx.setStorage({
      key: 'lujing',
      data: 'send_info/send_info',
    })
    wx.navigateTo({
      url: '/pages/address/address',
    })
    
    // wx.chooseLocation({

    //   success: function (res) {
    //     that.setData({
    //       c_location: formatLocation(res.longitude, res.latitude),
    //       locationAddress: res.address,
    //       c_latitude:res.latitude,
    //       c_longitude:res.longitude
    //     })
       
    //     var lishi_len = lishi.length;
     
    //     if (lishi_len == 0){
    //       lishi.push(res);
    //     }else{
    //       var i;
    //       for (i=0; i < lishi_len;){
           
    //         if (res.address != lishi[i].address){
    //              i++;
    //         }else{
    //           return;
    //         }
    //       }
    //       if(i==lishi_len){
    //         lishi.push(res);
    //       }
         
    //     }
    //     console.log("****************lishidizhi*************")
    //     console.log("数组的长度"+lishi.length)
    //     console.log(lishi);
    //     wx.setStorage({
    //       key: 'lishiSt',
    //       data: lishi,
    //     })
    //   }
    // })
  },

  //弹出常用地址列表
  pop_addr:function(){
    var that=this;
    console.log(app.userList.openid);
    //请求数据
    wx.request({
      url: jumpurl +'often/index',
      data:{
        openid:app.userList.openid
      },
      success:function(res){
        console.log(res);
        var changyong=res.data.changyong;
        if(changyong==0){
            that.setData({
              hasaddr:false
            })
        }else{
         
          that.setData({
            hasaddr: true,
            addrlist:res.data.changyong
          })

        }
      },
      fail:function(err){
          console.log(err);
      }
    })


    var that=this;
    that.setData({
      addr_grey_flag:true
    })
  },
  
//编辑
  edit:function(){
    wx.navigateTo({
      url: '/pages/addresslist/addresslist',
    })
    this.setData({
      addr_grey_flag: false
    })
  },
  
  //点击常用地址取消
  cancelBtn:function(){
    var that = this;
    that.setData({
      addr_grey_flag: false
    })
  },

 

  //点击常用地址列表  数据回填  隐藏经纬度一并回填
  choseItem:function(e){
    var that=this;
      console.log(e);
      var id=e.currentTarget.dataset.id;
      var chosedItem=id;
   
    wx.request({
      url: jumpurl+'huitian/index',
      data:{
        id:id,
        openid:app.userList.openid

      },
      success:function(res){
       
        console.log(res)
        var address=res.data.msg.message.address;
        var jingwei=res.data.msg.message.jingwei;
        var map_add=res.data.msg.message.map_add;
        var name=res.data.msg.message.name;
        var tel=res.data.msg.message.tel;
        that.setData({
         
          addr_grey_flag: false,
          setname: name,
          phone: tel,
          locationAddress: map_add,
          address2: address,
          jingwei: jingwei
        })
      },
      fail:function(err){
        console.log("回填地址"+err)
      }
    })
   
  },


  /*****表单验证**********/
  formBindsubmit: function (mobile) {
    var that = this;
    var jumpurl = app.jumpurl.url;
    var openid = app.userList.openid;
    var transmit = mobile.detail.value;
    // console.log("************transmit*************");
    // console.log(transmit);
    var mobile = transmit.phone; //传入首页的手机号
    var setname = transmit.setname;
    var name = transmit.setname; //传入首页的用户名

    var address_1 = transmit.address1; //传入首页的地址1
    var address_2 = transmit.address2; //传入首页的详细地址
    var jingwei = transmit.jingwei;
    
    // id_now=transmit.id_now;
     if (mobile.length == 0) {
      wx.showToast({
        title: '请输入手机号！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (mobile.length != 11) {
      wx.showToast({
        title: '手机号长度有误！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (!myreg.test(mobile)) {
      wx.showToast({
        title: '手机号有误！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    else{
    }
   
    
    if(!name){
      wx.showToast({
        title: '发货人姓名不能为空',
        icon:"none",
      })
      return false;
    }else if(!address_1){
      wx.showToast({
        title: '发货地址不能为空',
        icon:"none",
      })
      return false;
    }else{
      // wx.showToast({
      //   title: '验证成功',
      //   icon: "success",
      //   duration:1500
      // })
      // wx.reLaunch({
      //     url: '/pages/index/index?mobile=' + mobile + "&name=" + name + "&address_1=" + address_1 + "&address_2=" + address_2                  + "&id_now=" + id_now
      //   })

    }
   
   wx.request({
      url: jumpurl+'address/index',
      data:{
        openid:openid,
        name: setname,
        tel: mobile,
        map_add: address_1,
        address: address_2,
        jingwei: jingwei,
        types:0,
        currentTab: that.data.currentTab,
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //post
      },
      success:function(res){
        console.log("*************currentTab**********");
        console.log(that.data.currentTab);
        wx.setStorage({
          key: 'map_add_key',
          data: '',
        })
        wx.setStorage({
          key: 'title_key',
          data: '',
        })
        wx.setStorage({
          key: 'jingwei_key',
          data: '',
        })
        wx.reLaunch({
          url: '/pages/index/index?currentTab=' + that.data.currentTab
        })
        
      }
    })

 return true;
    
  },

// 点击下方地址选择回填到上方
  getadd:function(e){
    console.log("-------------------------------------")
    console.log(e)
    var map_add = e.currentTarget.dataset.address;
    var address=e.currentTarget.dataset.title;
    var jingwei=e.currentTarget.dataset.jingwei;
    this.setData({
      locationAddress: map_add,
      address2: address,
      jingwei: jingwei
    })
  },
  getadd2: function (e) {
    console.log("-------------------------------------")
    console.log(e)
    var map_add = e.currentTarget.dataset.map_add;
    var address = e.currentTarget.dataset.address;
    var jingwei = e.currentTarget.dataset.jingwei;
    this.setData({
      locationAddress: map_add,
      address2: address,
      jingwei: jingwei
    })
  },

/*******************************/
  changeMarkerColor: function (data, i) {
    var that = this;
    var markers = [];
    for (var j = 0; j < data.length; j++) {
      if (j == i) {
        // 此处需要在相应路径放置图片文件 
        data[j].iconPath = "../../img/marker_yellow.png";
      } else {
        // 此处需要在相应路径放置图片文件 
        data[j].iconPath = "../../img/marker_red.png";
      }
      markers[j](data[j]);
    }
    that.setData({
      markers: markers
    }); 

  },
  skiped:function(){
    // wx.navigateTo({
    //   url: '/pages/index/index',
    // })
  },
  footerTap: app.footerTap
})